package com.chao.controller;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class TestSendMsgQueue {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/sm")
    public void TestSendMsgQueue() {
        // 队列名称
        String queueName = "direct.queue_one";
        // 消息
        String message = "Hello,MQ!";
        // 发送消息
        rabbitTemplate.convertAndSend(queueName, message);
    }

    @GetMapping("/work")
    public void TestSendMsgWorkQueue() throws InterruptedException {
        // 队列名称
        String queueName = "work.queue";
        // 发送消息
        for (int i = 1; i <= 50; i++) {
            // 消息
            String message = "Hello,MQ! is for_" + i;
            rabbitTemplate.convertAndSend(queueName, message);
            Thread.sleep(20);
        }
    }

    @GetMapping("/fanout")
    public void TestSendMsgFanout() {
        // 交换机名称
        String fanoutName = "cg.fanout";
        // 消息
        String message = "Hello,MQ!--fanout";
        // 发送消息
        rabbitTemplate.convertAndSend(fanoutName, "", message);
    }

    @GetMapping("/direct")
    public void TestSendMsgDirect() {
        // 交换机名称
        String fanoutName = "cg.direct";
        // 消息
        String message = "Hello,MQ!--direct";
        // 指定key
        String key = "blue";
        // 发送消息
        rabbitTemplate.convertAndSend(fanoutName, key, message);
    }

    /**
     * 发送object对象消息需要实现jackson序列化
     */
    @GetMapping("/objectMsg")
    public void TestSendObjectMsg() {
        // 交换机名称
        String queueName = "object.queue";
        // obj消息
        Map<String, Object> msg = new HashMap<>(2);
        msg.put("name", "jack");
        msg.put("age", 24);
        rabbitTemplate.convertAndSend(queueName, msg);
    }

    // 发送一百万条消息
    /**
     * 发送object对象消息需要实现jackson序列化
     */
    @GetMapping("/testProperty")
    public void testProperty() {
        // 设置消息为不持久化
        Message message = MessageBuilder
                .withBody("hello".getBytes())
                .setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT).build();

        // // 设置消息为持久化
        // Message message = MessageBuilder
        //         .withBody("hello".getBytes())
        //         .setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();

        // 记得关闭 消息回调 yml中 不然很慢
        for (int i = 0; i < 1000000; i++) {
            rabbitTemplate.convertAndSend("simple.queue", message);
        }
    }
}
